package com.spark.lola.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spark.lola.feign.service.PortalServiceOpenApi;
import com.spark.lola.logistics.entity.DriverInfo;
import com.spark.lola.logistics.service.DriverInfoService;
import com.spark.lola.logistics.util.RedisManage;
import com.spark.lola.support.api.constant.ApiConstants;
import com.spark.lola.support.api.entity.EnterpriseTokenUser;
import com.spark.lola.support.api.service.JwtService;
import com.spark.lola.support.common.constant.CommonConstant;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.GeneratorUtil;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.core.param.LoginRequest;
import com.spark.lola.support.wms.configuration.WmsProperties;
import com.spark.lola.support.wms.constant.SmsCodeConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.spark.lola.support.core.param.MessageParam;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: Zhi-peng wang
 * @date: 2020/05/21 13:58
 **/
@RestController
@RequestMapping(value = "/api/huarong/auth", produces = "application/json;charset=utf-8")
@Api(value = "/api/huarong/auth", tags = "授权")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private RedisManage redisManage;

    @Autowired
    private PortalServiceOpenApi portalServiceOpenApi;

    @Autowired
    private DriverInfoService driverInfoService;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private WmsProperties wmsProperties;

    @ApiOperation(value = "获取验证码")
    @ApiImplicitParam(name = "username", value = "账户名", required = true, dataType = "string", paramType = "path")
    @RequestMapping(value = "/getCode/{username}", method = RequestMethod.POST)
    public ResponseBean getCode(@PathVariable String username) {
        logger.info("===用户【{}】尝试获取验证码 ===START===", username);
        ResponseBean responseBean = portalServiceOpenApi.findByName(username);
        if (responseBean.getCode() != 200) {
            logger.info("===用户【{}】尝试获取验证码（{}） 失败===End===", username, responseBean.getDescription());
            return responseBean;
        }
        ShiroUser shiroUser = JSONObject.parseObject(JSONObject.toJSONString(responseBean.getData()), ShiroUser.class);
        String random = String.valueOf(GeneratorUtil.getRandomNumber(100000, 999999));
        redisManage.cache(username, random, 5, TimeUnit.MINUTES);
        logger.info("===用户【{}】尝试获取验证码（{}） 成功===End===", username, random);

        MessageParam messageParam = new MessageParam();
        List<String> list = new ArrayList<>();
        list.add(shiroUser.getPhone());
        messageParam.setMobiles(list);
        messageParam.setTplCode(SmsCodeConstant.VERIFICATION_CODE);
        Map<String, String> map = new HashMap<>();
        map.put("code", random);
        messageParam.setParams(map);
        return portalServiceOpenApi.sendMessage(messageParam);
    }

    @ApiOperation(value = "登录")
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json;charset=UTF-8")
    public ResponseBean login(@RequestBody LoginRequest request, HttpServletRequest httpServletRequest) {
        logger.info("===用户【{}】尝试登录===START===", request.getUsername());
        ResponseBean responseBean = portalServiceOpenApi.login(request.getUsername(), request.getPassword());
        if (responseBean.getCode() != 200) {
            return responseBean;
        }
        ShiroUser shiroUser = JSONObject.parseObject(JSONObject.toJSONString(responseBean.getData()), ShiroUser.class);
//        if (!redisManage.validate(request.getUsername())) {
//            return ResponseBean.error("验证码已过期!");
//        }
//        if (!redisManage.getValue(request.getUsername()).equals(request.getCode())) {
//            return ResponseBean.error("验证码不正确!");
//        }
        String token = null;
        // 判断是否是驾驶员
        if (request.getCode().equals("logistics") && wmsProperties.getLogistics().getDutyId().get(1).equals(shiroUser.getDutyId())) {
            if (shiroUser.getId() != 528) {
                if (!driverInfoService.empIdExists(shiroUser.getId())) {
                    return ResponseBean.error("当前账号未绑定驾驶员");
                }
                QueryWrapper<DriverInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("emp_id", shiroUser.getId());
                DriverInfo driverInfo = driverInfoService.list(queryWrapper).get(0);
                if (driverInfo.getUsed().equals(CommonConstant.N)) {
                    return ResponseBean.error("当前用户已禁用,请联系客服人员!");
                }
            }
            // 写入会话缓存
            EnterpriseTokenUser<?> enterpriseTokenUser = new EnterpriseTokenUser<>();
            enterpriseTokenUser.setShiroUser(shiroUser);
            token = jwtService.createToken(JSON.toJSONString(enterpriseTokenUser));
        }
        // 判断是否是业务员或接货员
        if ((request.getCode().equals("pur") && wmsProperties.getPurchase().getDutyId().get(1).equals(shiroUser.getDutyId())) ||
                (request.getCode().equals("receiving") && wmsProperties.getPurchase().getDutyId().get(2).equals(shiroUser.getDutyId()))) {
            // 写入会话缓存
            EnterpriseTokenUser<?> enterpriseTokenUser = new EnterpriseTokenUser<>();
            enterpriseTokenUser.setShiroUser(shiroUser);
            token = jwtService.createToken(JSON.toJSONString(enterpriseTokenUser));
        }
        if (token == null) {
            return ResponseBean.error("账户异常，请联系管理员!");
        }
        redisManage.delete(request.getUsername());
        logger.info("===用户【{}】尝试登录【token：{}】 成功===END===", request.getUsername(), token);
        return ResponseBean.success(token);
    }

    @ApiOperation(value = "退出")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public ResponseBean logout(HttpServletRequest request) {
        request.getSession().removeAttribute(ApiConstants.SESSION_PREFIX);
        return ResponseBean.success();
    }

}
